package com.ymttest.business.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.json.JSONObject;

import com.google.gson.GsonBuilder;
import com.ymatou.iapi.productmanager.parameter.product.AddSellerProductRequest;
import com.ymatou.iapi.productmanager.parameter.product.CatalogPropertySaveModel;
import com.ymatou.iapi.productmanager.parameter.product.CatalogSaveModel;
import com.ymatou.iapi.productmanager.parameter.product.ProductDescSaveModel;
import com.ymatou.iapi.productmanager.parameter.product.ProductFreightSaveModel;
import com.ymatou.iapi.productmanager.parameter.product.ProductPropertySaveModel;
import com.ymatou.iapi.productmanager.parameter.product.ProductSaveModel;
import com.ymatou.iapi.productmanager.parameter.product.ProductVideoSaveModel;
import com.ymatou.iapi.selleractivity.service.ApplyActivityCall;
import com.ymatou.iapi.shoppingcartservice.parameter.ShoppingcartProductBean;
import com.ymt.core.tool.Logger;
import com.ymttest.database.annotation.SqlMapperFactory;
import com.ymttest.database.annotation.product.IntergratedProductMapper;
import com.ymttest.database.model.YmtProductsInActivity;
import com.ymttest.database.mongo.YmtMongoDriverFactroy;
import com.ymttest.database.sqlwapper.YmtLiveWapper;
import com.ymttest.database.sqlwapper.YmtProductsInActivityWapper;
import com.ymttest.database.sqlwapper.YmtProductsInLiveWapper;
import com.ymttest.utils.JsonBeanHelper;
import com.ymttest.utils.MapUtil;
import com.ymttest.utils.YMTDateUtil;
import com.ymttest.utils.compare.AssertHelper;

public class AddProductCallService {
	//发布商品 发布活动 商品参加活动
	public static int getProdPriceWithActivity(int sellerId, String productId,Map<String, Object> activityMap) throws Exception {

		// 创建活动
		int activityId = ActivityCallService.createActivityInProcess(activityMap);
		Logger.comment("活动id: " + activityId);

		// 报名活动
		ApplyActivityCall.applyProductInActivity(sellerId, productId, activityId, MapUtil.hashMap());

		YmtProductsInActivityWapper ymtProductsInActivityWapper = new YmtProductsInActivityWapper();
		YmtProductsInActivity productsInActivity = ymtProductsInActivityWapper.selectByProductId(productId);
		int productInActivityId = productsInActivity.getIproductinactivityid();
		Logger.comment("活动商品id: " + productInActivityId);

		// 开始活动二审
		AdminCallService.approveProductInActivity(String.valueOf(productInActivityId));

		return productInActivityId;
	}
	
	//get bean by file
	public static AddSellerProductRequest getAddSellerProductRequestFromFile(String fileName,Map<String,Object> updateMap){
		if (fileName==null || fileName.equals("")){
			fileName = "addsellerproductcalltpl.json";
		}
		
		if (updateMap==null){
			updateMap = new HashMap<>();
		}
		
		String fullPath = "com.ymatou.iapi.productmanager/AddSellerProductCall/"+fileName+".json";
		
		JSONObject jsonBean = JsonBeanHelper.getJsonBean(fullPath);
		
		if (!updateMap.keySet().contains("product->productName")){
			updateMap.put("product->productName","自动化测试_"+ YMTDateUtil.getSysTime("yyyy-MM-dd-HH-mm-ss-SSS"));
		}
		
		JsonBeanHelper.updateJsonBean(jsonBean, updateMap);
		
	    String jsonStr = jsonBean.toString();
		
	    return  new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss")
								 .create()
								 .fromJson(jsonStr, AddSellerProductRequest.class);
		
		
	}
	
	
	public static void checkAddProduct(String productId,AddSellerProductRequest addSellerProductRequest) throws Exception{
		AddSellerProductRequest actInSql = new AddSellerProductRequest();
		ProductSaveModel productSaveModel = new ProductSaveModel();
		actInSql.setProduct(productSaveModel);
		
		IntergratedProductMapper ipm = SqlMapperFactory.getIntergratedProductMapper();
		
		//品牌名从库里拿
		String brandEn = ipm.selectBrandByBrandId(addSellerProductRequest.getProduct().getBrandId()).get("sBrandEn").toString();
		addSellerProductRequest.getProduct().setBrandName(brandEn);
		
		// SQL Products 
		Map<String,Object> productInMap = ipm.selectProductByProdId(productId);
		actInSql.setSellerId((Integer)productInMap.get("iUserId"));
		actInSql.setSellerName(productInMap.get("SellerLoginId").toString());
		actInSql.setProductSite(productInMap.get("sSiteId").toString());
		
		productSaveModel.setSpuId((Integer)productInMap.get("iSpuId"));
		productSaveModel.setProductName(productInMap.get("sProduct").toString());
		productSaveModel.setThirdCategoryId((Integer)productInMap.get("iThirdCategoryId"));
		productSaveModel.setSecondCategoryId((Integer)productInMap.get("iCategoryId"));
		productSaveModel.setBrandId((Integer)productInMap.get("iBrandId"));
		productSaveModel.setBrandName(productInMap.get("sBrand").toString());
		productSaveModel.setCatalogStatus((Integer)productInMap.get("iCatalogStatus"));
		productSaveModel.setNoReasonReturn((Boolean)productInMap.get("bNoticeRisk"));
		productSaveModel.setValidStart(productInMap.get("validStart").toString());
		productSaveModel.setValidEnd(productInMap.get("validEnd").toString());
		productSaveModel.setAutoRefresh((Boolean)productInMap.get("bAutoRefresh"));
		productSaveModel.setCatalogType((Integer)productInMap.get("iCatalogType"));
		productSaveModel.setTariffType((Integer)productInMap.get("iTariffType"));
		productSaveModel.setBondedArea((Integer)productInMap.get("iBondedArea"));
		productSaveModel.setProductCode((productInMap.get("sProductCode") == null) ? null : productInMap.get("sProductCode").toString());
		productSaveModel.setNoReasonReturn((Boolean)productInMap.get("bNoReasonReturn"));
		productSaveModel.setMultiLogistics((Integer)productInMap.get("iMultiLogistics"));
		productSaveModel.setFlightBalance(new BigDecimal(productInMap.get("dFlightBalance").toString()).doubleValue());
		productSaveModel.setWeightUnit((Integer)productInMap.get("WeightUnit"));
		productSaveModel.setSellerCountryId((Integer)productInMap.get("SellerCountryId"));
		//图片 商品表保存首图
		Logger.verifyEquals(addSellerProductRequest.getProduct().getProductPicList().get(0),
			productInMap.get("sPicUrl").toString(), "YmtProduct商品表保存首图");
		
		//validstart validend
		Date reqStartDate = YMTDateUtil.getDate(addSellerProductRequest.getProduct().getValidStart(),YMTDateUtil.YMDHMS);
		Date reqEndDate = YMTDateUtil.getDate(addSellerProductRequest.getProduct().getValidEnd(),YMTDateUtil.YMDHMS);
		Date startDateInSql = (Date)productInMap.get("validStart");
		Date endDateInSql = (Date)productInMap.get("validEnd");
		
		AssertService.assertTime(reqStartDate, startDateInSql, "validstart");
		AssertService.assertTime(reqEndDate, endDateInSql, "validend");
	
		
		
		//ProductPicture
		List<String> productPics = ipm.selectPictureByProdIdAndAction0(productId).stream()
								.map(x->x.get("sOriUrl").toString())
								.collect(Collectors.toList());
		productSaveModel.setProductPicList(productPics);
		
		
		
		
		//文描节点
		setProductDescSaveModel(productId,addSellerProductRequest,productSaveModel);
		
		//视频节点
		setproductVideoSaveModel(productId,addSellerProductRequest,productSaveModel);
		
		//属性
		setProductPropertySaveModel(productId,addSellerProductRequest,productSaveModel);
		
		//运费模板
		setProductFreightSaveModel(productId,addSellerProductRequest,productSaveModel);
		
		
		//规格
		setCatalogSaveModel(productId,addSellerProductRequest,productSaveModel);
		
		
		
		
		/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		
		//直播检查
		checkProductLive(addSellerProductRequest.getSellerId(),productId,addSellerProductRequest.getProduct().getLiveIdList());
		
		
		
		//商品等级检查
		String prodGrade = getProductGrade(addSellerProductRequest.getProduct());
		Logger.verifyEquals(prodGrade,productInMap.get("sGrade").toString(),"Grade检查");
		
		
		//检查对象bean
		AssertHelper.assertResultEqual(addSellerProductRequest, actInSql, "AddProduct Check");
		
		
		
		
		
		///////////////////////////////////////////////////////////////////////////////////
		//mongo 检查
		checkProductMgo(productId, addSellerProductRequest);
		
		
		
		
		
	}
	
    private static String getProductGrade(ProductSaveModel product) {
        if (product == null || product.getDescModel() == null
                || product.getDescModel().getDescription()== null) {
            return "C";
        }

        if (product.getDescModel().getDescPicList().isEmpty()) {
            return "C";
        }

        return product.getProductPicList().isEmpty() || product.getProductPicList().size() < 3
                ? "C" : "B";
    }
	
    
    
    //check 直播商品
	@SuppressWarnings("unchecked")
	private static void checkProductLive(int sellerId,String productId, List<Integer> liveIds) throws Exception {
		if (liveIds == null || liveIds.size() == 0) {
			return;
		}

		for (int liveId : liveIds) {
			Map<String, Object> liveMapUpdate = new YmtLiveWapper().selectforMapByLiveId(liveId).get(0);
			boolean isLiveStart = false;
			if (((Date) liveMapUpdate.get("dBeginTime")).before(YMTDateUtil.getDate())
					&& ((Date) liveMapUpdate.get("dEndTime")).after(YMTDateUtil.getDate())) {
				isLiveStart = true;
			}

			Map<String, Object> liveProductMap = new YmtProductsInLiveWapper().selectInLiveByProdIdAndLiveId(productId,liveId).get(0);
					

			Logger.verifyEquals(sellerId, Integer.parseInt(liveProductMap.get("iUserId").toString()),
					"ProductInLive - iUserId");
			Logger.verifyEquals(liveId, Integer.parseInt(liveProductMap.get("iActivityId").toString()),
					"ProductInLive - iActivityId");
			Logger.verifyEquals(0, Integer.parseInt(liveProductMap.get("iAction").toString()),
					"ProductInLive - iaction");

			AssertService.assertTime((Date) liveMapUpdate.get("dEndTime"), (Date) liveProductMap.get("dEndTime"), 10,
					"ProductInLive - endtime");

			if (isLiveStart) {
				AssertService.assertTime(YMTDateUtil.getDate(), (Date) liveProductMap.get("dStartTime"), 120,
						"ProductInLive - startTime");
				Logger.verifyEquals(1, Integer.parseInt(liveProductMap.get("iSellStatus").toString()),
						"ProductInLive - iSellStatus");
			} else {
				AssertService.assertTime((Date) liveMapUpdate.get("dBeginTime"),
						(Date) liveProductMap.get("dStartTime"), 120, "ProductInLive - startTime");
				Logger.verifyEquals(0, Integer.parseInt(liveProductMap.get("iSellStatus").toString()),
						"ProductInLive - iSellStatus");

			}
		}
    	
    	
    	
    }
    
    //check mongo
    private static void checkProductMgo(String productId,AddSellerProductRequest addSellerProductRequest) throws Exception{
    	if (YmtMongoDriverFactroy.IsNewJavaMongoOpen){
			List<Integer> liveIds = addSellerProductRequest.getProduct().getLiveIdList();
			if (liveIds == null || liveIds.size()==0){
				NewJavaMongoCheckService.checkProductMgoSyncBySQL_NewJavaMgo(productId);
			}else{
				for(Integer lid :liveIds ){
					NewJavaMongoCheckService.checkLiveMgoSyncBySQL_NewJavaMgo(lid, productId);
				}
			}
		}
    }
    
    
	//文描节点
	private static void setProductDescSaveModel(String productId,AddSellerProductRequest addSellerProductRequest,ProductSaveModel productSaveModel){
		ProductDescSaveModel  productDescSaveModel = new ProductDescSaveModel();
		
		//ProductDescConfigWord
		IntergratedProductMapper ipm = SqlMapperFactory.getIntergratedProductMapper();
		List<Map<String,Object>> prodConfigWordList = ipm.selectDescConfigWordByProdIdAndSellerId(productId, addSellerProductRequest.getSellerId());
		Logger.verifyEquals(1, prodConfigWordList.size(), "ProductDescConfigWord 文描记录应只有一条");
		Logger.verifyEquals(true, (Boolean)prodConfigWordList.get(0).get("Status"), "ProductDescConfigWord status 应为1");
		productDescSaveModel.setDescription(prodConfigWordList.get(0).get("WordContent").toString());
		
		
		//ProductDescConfigPicture
		List<String> prodConfigPicList = ipm.selectDescConfigPictureByProdIdAndSellerId(productId, addSellerProductRequest.getSellerId()).stream()
															.map(x->x.get("PictureUrl").toString()).collect(Collectors.toList());
		productDescSaveModel.setDescPicList(prodConfigPicList);
		
		//Ymt_ProductDescMap
		List<Map<String,Object>> descMapList = ipm.selectDescMapPByProdId(productId);
		
		if (addSellerProductRequest.getProduct().getDescModel().getBuyerNoticeId()>0||
				addSellerProductRequest.getProduct().getDescModel().getDeclarationId()>0 || 
				addSellerProductRequest.getProduct().getDescModel().getSellerServiceId()>0 ||
				addSellerProductRequest.getProduct().getDescModel().getSizeTemplateId()>0)
		{
			Logger.verifyEquals(1, descMapList.size(), "Ymt_ProductDescMap 记录应只有一条");
			productDescSaveModel.setSizeTemplateId((Integer)descMapList.get(0).get("SizeTemplateId"));
			productDescSaveModel.setBuyerNoticeId((Integer)descMapList.get(0).get("BuyerNoticeId"));
			productDescSaveModel.setSellerServiceId((Integer)descMapList.get(0).get("SellerServiceId"));
			productDescSaveModel.setDeclarationId((Integer)descMapList.get(0).get("DeclarationId"));
		}else{
			Logger.verifyEquals(0, descMapList.size(), "Ymt_ProductDescMap 记录应没有");
		}
		
		
		productSaveModel.setDescModel(productDescSaveModel);
	}
	
	//视频节点
	private static void setproductVideoSaveModel(String productId,AddSellerProductRequest addSellerProductRequest,ProductSaveModel productSaveModel) {
		// Ymt_ProductVideo
		IntergratedProductMapper ipm = SqlMapperFactory.getIntergratedProductMapper();
		List<Map<String, Object>> prodVideoList = ipm.selectProdVideoByProdId(productId,
				addSellerProductRequest.getSellerId());

		if (addSellerProductRequest.getProduct().getVideoModel() != null) {
			Logger.verifyEquals(1, prodVideoList.size(), "Ymt_ProductVideo 记录应只有1条");
			ProductVideoSaveModel productVideoSaveModel = new ProductVideoSaveModel();
			productVideoSaveModel.setVideoUrl(prodVideoList.get(0).get("VideoUrl").toString());
			productVideoSaveModel.setLength((Integer) prodVideoList.get(0).get("VideoLength"));
			productVideoSaveModel.setPic(prodVideoList.get(0).get("VideoPic").toString());
			productVideoSaveModel.setWidth((Integer) prodVideoList.get(0).get("VideoWidth"));
			productVideoSaveModel.setHeight((Integer) prodVideoList.get(0).get("VideoHeight"));
			productVideoSaveModel.setSize((Integer) prodVideoList.get(0).get("VideoSize"));

			productSaveModel.setVideoModel(productVideoSaveModel);
		} else {
			Logger.verifyEquals(0, prodVideoList.size(), "Ymt_ProductVideo 记录应没有");
		}
	}
	
	//属性
	private static void setProductPropertySaveModel(String productId,AddSellerProductRequest addSellerProductRequest,ProductSaveModel productSaveModel){
		// Ymt_ProductProperty
		IntergratedProductMapper ipm = SqlMapperFactory.getIntergratedProductMapper();
		List<Map<String, Object>> prodPropertyList = ipm.selectPropertyByProdId(productId);
		List<ProductPropertySaveModel> propertyList = new ArrayList<>();

		if (addSellerProductRequest.getProduct().getPropertyList() == null
				|| addSellerProductRequest.getProduct().getPropertyList().size() == 0) {
			Logger.verifyEquals(0, prodPropertyList.size(), "Ymt_ProductProperty 记录应没有");
		} else {
			prodPropertyList.forEach(ele -> {
				ProductPropertySaveModel productPropertySaveModel = new ProductPropertySaveModel();
				productPropertySaveModel.setPropertyId((Integer) ele.get("PropertyId"));
				productPropertySaveModel.setPropertyValues(Arrays.asList(ele.get("Value").toString().split(",")));
				propertyList.add(productPropertySaveModel);
			});

		}
		productSaveModel.setPropertyList(propertyList);
				
	}
	
	//运费模板
	private static void setProductFreightSaveModel(String productId,AddSellerProductRequest addSellerProductRequest,ProductSaveModel productSaveModel){
		// Ymt_ProductDeliveryTemplate
		IntergratedProductMapper ipm = SqlMapperFactory.getIntergratedProductMapper();
		List<Integer> tplIdList = addSellerProductRequest.getProduct().getFreightTemplateList().stream()
				.map(x -> x.getTemplateId()).collect(Collectors.toList());
		List<ProductFreightSaveModel> delTplModelList = new ArrayList<>();

		for (Integer tplId : tplIdList) {
			List<Map<String, Object>> prodTplList = ipm.selectDeliveryTplByProductIdAndTplId(productId, tplId);
			Logger.verifyEquals(1, prodTplList.size(), "Ymt_ProductDeliveryTemplate 记录应只有一条");
			ProductFreightSaveModel productFreightSaveModel = new ProductFreightSaveModel();
			productFreightSaveModel.setTemplateId(tplId);
			productFreightSaveModel.setCatalogStatus((Integer) prodTplList.get(0).get("CatalogStatus"));
			delTplModelList.add(productFreightSaveModel);
		}

		productSaveModel.setFreightTemplateList(delTplModelList);
	}

	//规格
	private static void setCatalogSaveModel(String productId,AddSellerProductRequest addSellerProductRequest,ProductSaveModel productSaveModel){
		List<CatalogSaveModel> catalogList = new ArrayList<>();
		//catalogs
		IntergratedProductMapper ipm = SqlMapperFactory.getIntergratedProductMapper();
		
		List<Map<String,Object>> catalogsInSqlMap = ipm.selectCatalogsByProdId(productId);
		 
		for(Map<String,Object> catalogMap : catalogsInSqlMap){
			CatalogSaveModel catalogSaveModel = new CatalogSaveModel();
			catalogSaveModel.setCatalogId(catalogMap.get("sCatalogId").toString());			
			catalogSaveModel.setPackage((Boolean)catalogMap.get("IsPackage"));
			catalogSaveModel.setMultiLogistics((Integer)catalogMap.get("iMultiLogistics"));
			catalogSaveModel.setPrice(new BigDecimal(catalogMap.get("fQuotePrice").toString()).doubleValue());
			catalogSaveModel.setVipPrice(new BigDecimal(catalogMap.get("fVipPrice").toString()).doubleValue());
			catalogSaveModel.setNewPrice(new BigDecimal(catalogMap.get("fNewCustomerPrice").toString()).doubleValue());
			catalogSaveModel.setStock((Integer)catalogMap.get("iNum"));
			catalogSaveModel.setSku((catalogMap.get("sSKU") == null) ? null : catalogMap.get("sSKU").toString());
			catalogSaveModel.setProductCode((catalogMap.get("sProductCode") == null) ? null : catalogMap.get("sProductCode").toString());
			catalogSaveModel.setPreSale((Boolean)catalogMap.get("IsPreSale"));
			catalogSaveModel.setWeight(new BigDecimal(catalogMap.get("Weight").toString()).doubleValue());
			catalogSaveModel.setOperateType(1);
			catalogSaveModel.setAction((Integer)catalogMap.get("iAction"));
			
			
			//获取该规格有效
			List<Integer> subCatalogList = ipm.selectSubCatalogByCatalogId(catalogMap.get("sCatalogId").toString())
								.stream().filter(x->(Integer)x.get("Action")>-1)
								.map(y->(Integer)y.get("SubCatalogId"))
								.collect(Collectors.toList());
			
			catalogSaveModel.setSubCatalogIdList(subCatalogList.size()==0?null:subCatalogList);
			
			
			
			
			
			//属性
			List<CatalogPropertySaveModel> propertyList = new ArrayList<>();
			List<Map<String,Object>> proAndValMapList = ipm.selectCatalogProAndValByCatalogId(catalogMap.get("sCatalogId").toString());
			
			for(Map<String,Object> proAndValMap: proAndValMapList){
				CatalogPropertySaveModel catalogPropertySaveModel = new CatalogPropertySaveModel();
				catalogPropertySaveModel.setPropertyName(proAndValMap.get("sProductProperty").toString());
				catalogPropertySaveModel.setPropertyValue(proAndValMap.get("sCategoryAttribute").toString());
				catalogPropertySaveModel.setPropertyUrl((proAndValMap.get("sPicUrl") == null) ? null : proAndValMap.get("sPicUrl").toString());
				propertyList.add(catalogPropertySaveModel);
			}
			
			catalogSaveModel.setPropertyList(propertyList);
			catalogList.add(catalogSaveModel);
		}
		productSaveModel.setCatalogList(catalogList);
		
		
		
		//找到对应匹配请求的规格 设置catalog值 
		List<String> catalogIds = catalogsInSqlMap.stream().map(x->x.get("sCatalogId").toString()).collect(Collectors.toList());
		List<CatalogSaveModel> catalogListReq = addSellerProductRequest.getProduct().getCatalogList();
		Logger.verifyEquals(catalogIds.size(), catalogListReq.size(), "addProduct 规格数应该与数据库相同");
		
		if (catalogListReq.size()==1){
			//单规格
			catalogListReq.get(0).setCatalogId(catalogIds.get(0));
		}else{
			//多规格
			for (CatalogSaveModel catalogSaveModelReq:catalogListReq){
				if (catalogSaveModelReq.getPropertyList().size()==1){
					//单属性
					String property  = catalogSaveModelReq.getPropertyList().get(0).getPropertyValue();
					CatalogSaveModel sqlCatalog = productSaveModel.getCatalogList().stream()
															.filter(x->x.getPropertyList().get(0).getPropertyValue().equals(property))
															.findFirst().orElse(null);
					Logger.verifyIsNull(sqlCatalog, "该属性应该存在规格:["+property+"]");
					catalogSaveModelReq.setCatalogId(sqlCatalog.getCatalogId());
					
				}else{
					//双属性
					String property1 = catalogSaveModelReq.getPropertyList().get(0).getPropertyValue();
					String property2 = catalogSaveModelReq.getPropertyList().get(1).getPropertyValue();
					CatalogSaveModel sqlCatalog = productSaveModel.getCatalogList().stream()
							.filter(x->(x.getPropertyList().get(0).getPropertyValue().equals(property1) && x.getPropertyList().get(1).getPropertyValue().equals(property2))
										||(x.getPropertyList().get(1).getPropertyValue().equals(property1) && x.getPropertyList().get(0).getPropertyValue().equals(property2)))
										.findFirst().orElse(null);
					
					Logger.verifyNotNull(sqlCatalog, "该属性应该存在规格:["+property1+","+property2+"]");		
					catalogSaveModelReq.setCatalogId(sqlCatalog.getCatalogId());
				}
			}
		}
		
		
		
		
		
		
		
		
		
		
	}
}
